﻿/// <reference path="ItemIn.js" />
var accountinfo = {
    
    bindInfo: function () {
        $.ajax({
            url: "/Handler/AccountHandler.ashx",
            type: "GET",
            data: { t: "GetAssets", gateWayId:pages_paymentIn_ItemIn.gateWayId },
            dataType: "json",
            contentType: "application/json",
            success: function (data) {
                $("#spTotalAu").html(COMMON.formatMoney(data.Au));
                $("#spTotalBlance").html(COMMON.formatMoney(data.Blance));
                //$("#spTotalAg").html(COMMON.formatMoney(data.Ag));
            },
            error: function () {

            }
        });
    }
};


var slotMachine = {
    gateWayId:0,
    sounds: {},
    //event click button here
    init: function () {
        try {
            accountinfo.bindInfo();
        } catch (e) {

        }

        $('#betSpinUp').click(function () {
            var bet = parseInt($('#txtBet').val());
            if (!(bet > 0))
                bet = 0;
            if (bet < 100)
                bet = 100;
            else
                bet += 50;
            $('#txtBet').val(bet);

        });
        $('#betSpinDown').click(function () {
            var bet = parseInt($('#txtBet').val());
            if (!(bet > 0))
                bet = 0;
            if (bet <= 100)
                bet = 100;
            else
                bet -= 50;
            $('#txtBet').val(bet);
        });

        $('#spinButton').click(function () {
            var type = 1; // $('#ddlTypeBet').val();
            var money = $('#txtBet').val();
            slotMachine.spin(this, type, money, 0, 0);
        });
        this.disableBet_style(false, 100, 1);
        $('#btnChoose_h1').click(function () { slotMachine.spin(this, 0, 0, 1, 1); });
        $('#btnChoose_h2').click(function () { slotMachine.spin(this, 0, 0, 1, 2); });
        $('#btnChoose_h3').click(function () { slotMachine.spin(this, 0, 0, 1, 3); });

        $('#btnChoose_l1').click(function () { slotMachine.spin(this, 0, 0, 0, 1); });
        $('#btnChoose_l2').click(function () { slotMachine.spin(this, 0, 0, 0, 2); });
        $('#btnChoose_l3').click(function () { slotMachine.spin(this, 0, 0, 0, 3); });

        $('#btnShuffle').click(function () { slotMachine.spin(this, 0, 0, 0, 0); });
        $('#btnCollect').click(function () { slotMachine.collect(); });
        $('#soundOffButton').click(function () { slotMachine.toggle_sound(); });

        try {
            soundManager.setup({
                // custom demo options, not for your needs
                debugMode: false,
                url: '/soundmanager/'
            });
            soundManager.onready(function () {
                slotMachine.sounds['payout'] = soundManager.createSound({ id: "payout", url: '/triple7/payout.mp3' });
                slotMachine.sounds['fastpayout'] = soundManager.createSound({ id: "fastpayout", url: '/triple7/fastpayout.mp3' });
                slotMachine.sounds['spinning'] = soundManager.createSound({ id: "spinning", url: '/triple7/spinning.mp3' });
            });
        } catch (e) {

        }

    },

    disableBet_style: function (isDisable, money, typebet) {
        if (money > 0) {
            $('#txtBet').val(money);
            $('#ddlTypeBet').val(typebet);
        }
        if (isDisable) {
            $("#divBet").hide();
            $("#divShuffule").show();

            $('#txtBet').attr('disabled', 'disabled');
            $('#ddlTypeBet').attr('disabled', 'disabled');
            $('#spinButton').addClass('disabled');

        } else {
            $("#divBet").show();
            $("#divShuffule").hide();

            $('#txtBet').removeAttr('disabled');
            $('#ddlTypeBet').removeAttr('disabled');
            $('#spinButton').removeClass('disabled');
        }
    },

    //----------------------------------------------------
    toggle_sound: function () {
        if ($('#soundOffButton').hasClass("off")) {
            try {
                soundManager.unmute();
            } catch (e)
            { }
        } else {
            try {
                soundManager.mute();
            } catch (e)
            { }
        }
        $('#soundOffButton').toggleClass("off");
    },

    //----------------------------------------------------
    //Type=0: Chọn cao/thấp
    //Type=1: Đặt vàng
    //Type=2: Đặt bạc
    //
    //hi: 1.cao, 2. thấp, 0. shuffle
    //col: Cột(1,2,3)
    spin: function (obj, type, bet, hi, col) {


        if ($(obj).hasClass("disabled")) { return false; }

        // Clean up the UI
        slotMachine.show_won_state(0);

        this.disabledAll();
        this.disableBet_style(true, bet, type);

        // Make the reels spin
        slotMachine._start_reel_spin(1);
        slotMachine._start_reel_spin(2);
        slotMachine._start_reel_spin(3);

        try {
            slotMachine.sounds['spinning'].play();
        } catch (err) { }

        // We need to make the reels end spinning at a certain time, synched with the audio, independently of how long the AJAX request takes.
        // Also, we can't stop until the AJAX request comes back. So we must have a timeout for the first reel stop, and a function that makes
        //   the magic happen, and whatever happens last (this timeout, or the AJAX response) calls this function.
        // The sound timings are at: 917ms, 1492ms and 2060ms, which needs to be adjusted by the animation timings
        //   (which is why i'm setting the first one at 250ms before 917ms)

        var fnStopReelsAndEndSpin = function () {
            // Make the reels stop spinning one by one
            var baseTimeout = 0;
            window.setTimeout(function () { slotMachine._stop_reel_spin(1, spinData.Info.Column1Value); }, baseTimeout);
            baseTimeout += 575;
            window.setTimeout(function () { slotMachine._stop_reel_spin(2, spinData.Info.Column2Value); }, baseTimeout);
            baseTimeout += 568;
            window.setTimeout(function () { slotMachine._stop_reel_spin(3, spinData.Info.Column3Value); }, baseTimeout);

            baseTimeout += 700; // This must be related to the timing of the final animation. I'm making it a bit less, so the last reel is still bouncing when it lights up
            window.setTimeout(function () { slotMachine.end_spin(spinData); }, baseTimeout);
        };

        var FirstReelTimeoutHit = false;
        var spinData = null;
        window.setTimeout(function () { FirstReelTimeoutHit = true; if (spinData != null) { fnStopReelsAndEndSpin(); } }, 667);

        var mdata = {
            gateWayId:this.gateWayId,
            type: type,
            bet: bet,
            hi: hi,
            col: col
        };
        $.ajax({
            url: "/Service/WSGame.asmx/BetItem",
            type: "POST",
            data: JSON.encode(mdata),
            dataType: "json",
            contentType: "application/json",
            timeout: 10000,
            success: function (data) {
                data = data.d;
                if (!data.Success) {
                    slotMachine.abort_spin_abruptly();

                    if (data.Result == -100) {
                        var md = data.Mess.split('|');
                        var amount = md[0];
                        var unit = md[1];
                        var money = md[2];
                        var au = md[3];
                        var unitbet = type == 1 ? "vàng" : "bạc";
                        sConfirm("Thông báo", "Tài khoản của bạn không đủ để đặt cược!"
                            + "<br/>Bạn muốn sử dụng " + amount + " " + unit + " để thanh toán? "
                            + "<br/>(Bạn sẽ có thêm " + au + " "+unitbet+" và sẽ đặt cược " + money + " "+unitbet+(au-money>0? (", "+(au-money)+" "+unitbet+" sẽ cộng vào tài khoản"):"")+")"
                            , function () {
                                Loading.showProcess();
                                var money = 5;
                                var _data = {
                                    money: money,
                                    gateWayId: pages_paymentIn_ItemIn.gateWayId
                                };
                                $.ajax({
                                    type: "POST",
                                    url: "/Service/WSUser.asmx/GoBuyItemSingle",
                                    data: JSON.encode(_data),
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    cache: false,
                                    success: function (data) {
                                        Loading.closeProcess();
                                        var rel = data.d.split('|')[0];
                                        var mess = data.d.split('|')[1];
                                        if (rel == -1) {
                                            sAlert("Thông báo", "Bạn đã hết phiên đăng nhập");
                                            return;
                                        }
                                        if (rel > 0) {
                                            try {
                                                accountinfo.bindInfo();
                                            } catch (e) {

                                            }
                                            
                                            sAlert("Thông báo", "Bạn đã mua thành công", function () {
                                                slotMachine.spin($('#spinButton'), 1, 100, 0, 0);
                                            });
                                            return;
                                        } else {
                                            sAlert("Thông báo", mess);
                                        }
                                    }
                                });
                            });
                    } else {
                        sAlert("Thông báo", data.Mess);
                        if (data.Result == -1) {
                            window.location = data.UrlGetCode;
                        }
                    }

                    if (type > 0) {
                        slotMachine.disableBet_style(false, bet, type);
                    }

                    return false;
                }
                spinData = data;
                if (FirstReelTimeoutHit == true) { fnStopReelsAndEndSpin(); }
                if (type > 0) {
                    try {
                        accountinfo.bindInfo();
                    } catch (e) {

                    }
                }

            },
            error: function () {
                slotMachine.abort_spin_abruptly();
                //$('#failedRequestMessage').show();
                window.location = window.location;
            }
        });

    },
    collect: function () {
        if ($('#btnCollect').hasClass('disabled'))
            return false;
        this.disabledAll();
        $.ajax({
            url: "/Service/WSGame.asmx/Collect",
            type: "POST",
            data: null,
            dataType: "json",
            contentType: "application/json",
            //timeout: 10000,
            success: function (data) {
                var result = data.d.split('|')[0];
                var mess = data.d.split('|')[1];
                if (result > 0) {
                    slotMachine.disabledAll();

                    $("#totalBids").html(0);
                    $("#txtReel_h1").html(0);
                    $("#txtReel_h2").html(0);
                    $("#txtReel_h3").html(0);

                    $("#txtReel_l1").html(0);
                    $("#txtReel_l2").html(0);
                    $("#txtReel_l3").html(0);

                    $("#shuffle_bar").html('');

                    for (var i = 0; i < 6; i++) {
                        $("#shuffle_bar").append("<li><img src=\"/images/tg_2.jpg\" width=\"23\" height=\"23\" /></li>");
                    }

                    slotMachine.disableBet_style(false, 100, 1);
                    try {
                        accountinfo.bindInfo();
                    } catch (e) {

                    }
                } else {
                    sAlert('Thông báo', mess);
                }
            },
            error: function () {
                slotMachine.abort_spin_abruptly();
                //$('#failedRequestMessage').show();                                
                sAlert('Thông báo', 'Lỗi kết nối với máy chủ!');
                window.location = window.location;
            }
        });
    },
    show_won_state: function (result) {
        return;

        //Win
        if (result == 1) {
            $('.won_image').show();
            $('.lose_image').hide();
            $('#btnCollect').removeClass("disabled");
        }
        //Lost
        if (result == -1) {
            $('.won_image').hide();
            $('.lose_image').show();
            $('#btnCollect').addClass("disabled");
        }
        //Clean
        if (result == 0) {
            $('.won_image').hide();
            $('.lose_image').hide();
        } else {

            var tm = $('#divCollect').data('timeOutNo');
            window.clearTimeout(tm);
            var timeoutId = setTimeout(function () {
                $('.won_image').hide();
                $('.lose_image').hide();
                $('#divCollect').data('timeOutNo', null);
            }, 3000);
            $('#divCollect').data('timeOutNo', timeoutId);
        }

    },

    end_spin: function (data) {
        //if (data.exp_info) {update_experience_data(data.exp_info);}  // We're not sending this down anymore, since users don't get experience from spinning        
        if (data.Info.Result >= 0) {//không thua(thắng, đặt, shuffle)
            slotMachine._increment_payout_counter(data); // _increment_payout_counter will call end_spin_after_payout, which is where this list of things to do at the end really ends
        } else {
            $("#shuffle_bar").html('');
            for (var i = 0; i < 6; i++) {
                $("#shuffle_bar").append("<li><img src=\"/images/tg_2.jpg\" width=\"23\" height=\"23\" /></li>");
            }
            slotMachine._end_spin_after_payout(data);
        }
        this.show_won_state(data.Result);
    },

    // These are the things that need to be done after the payout counter stops increasing, if there is a payout
    _end_spin_after_payout: function (data) {
        // This is technically redundant, since the payout incrementer updated them, and we decreased it when spinning,
        //   but just in case something got off sync        

        if (data.Result == -1) {//game over
            //$('#lastWin').html(0);
            $('#totalBids').html(0);
            this.disableBet_style(false, 100, 1);
        } else {//win

            if (data.Info.Jackpot > 0) {
                sAlert('Thông báo', 'Chúc mừng bạn đã giật jackport ' + data.Info.Jackpot + ' vàng');
                try {
                    accountinfo.bindInfo();
                } catch (e) {

                }
            }
            $('.quay_nut1 a').removeClass("disabled");
            $('.quay_nut2 a').removeClass("disabled");
        }
        this.setValueRate(data);
    },

    _increment_payout_counter: function (data) {

        var money = data.Info.AuCurrent + data.Info.AgCurrent;
        var i = 0;
        var old = parseInt($('#totalBids').html());
        if (!(old > 0))
            old = data.Info.AuBet + data.Info.AgBet;
        $('#totalBids').html(old);
        var mWin = money - old;

        var soundName = 'payout'; // (money > 80 ? 'fastpayout' : 'payout');
        var tickDelay = (mWin > 80 ? 2 : 10);

        try {
            slotMachine.sounds[soundName].play({ onfinish: function () { this.play(); } });
        } catch (err) { }
        var timerID = window.setInterval(function () {
            i++;
            //$('#lastWin').html(i);
            $('#totalBids').html(old + i);

            if (i >= mWin) {
                window.clearInterval(timerID);

                try {
                    slotMachine.sounds[soundName].stop();
                } catch (err) { }

                slotMachine._end_spin_after_payout(data);
            }
        }, tickDelay);
    },

    abort_spin_abruptly: function () {
        slotMachine._stop_reel_spin(1, null);
        slotMachine._stop_reel_spin(2, null);
        slotMachine._stop_reel_spin(3, null);
        try {
            slotMachine.sounds['spinning'].stop();
        }
        catch (e) { }

    },

    // -----------------------------------

    _start_reel_spin: function (i) {
        var elReel = $('#reel' + i); // cache for performance
        elReel.css({ top: -(Math.random() * 1400) }); // Change the initial position so that, if a screenshot is taken mid-spin, reels are mis-aligned
        var curPos = parseInt(elReel.css("top"), 10);

        var fnAnimation = function () {
            elReel.css({ top: curPos });
            curPos += 100;
            if (curPos > 0) { curPos = -1456; }
        };
        var timerID = window.setInterval(fnAnimation, 20);
        elReel.data("spinTimer", timerID);
    },
    _stop_reel_spin: function (i, outcome, animate) {
        if (typeof (animate) == 'undefined')
            animate = true;

        var elReel = $('#reel' + i); // cache for performance
        var timerID = elReel.data("spinTimer");
        window.clearInterval(timerID);
        elReel.data("spinTimer", null);


        if (outcome != null) {
            // 1573 is the height of the whole strip, which repeats thrice, so we don't have to care about looping
            // 121 is the distance between icon centers, and 86 is kind of empirical...           
            var finalPosition = -1092 - ((outcome - 1) * 84) + 50;
            if (animate) {
                // Animation two: Elastic Easing
                elReel.css({ top: finalPosition - 1092 })
                    .animate({ top: finalPosition + 120 }, 120, 'linear', function () {
                        elReel.animate({ top: finalPosition }, 1000, 'easeOutElastic');
                    });
            } else {
                elReel.css('top', finalPosition + 'px');
            }
        }
    },
    _init_old_session: function (data) {
        this._stop_reel_spin(1, data.Info.Column1Value, false);
        this._stop_reel_spin(2, data.Info.Column2Value, false);
        this._stop_reel_spin(3, data.Info.Column3Value, false);

        this.setValueRate(data);
    },
    disabledAll: function () {
        $('.quay_nut1 a').addClass("disabled");
        $('.quay_nut2 a').addClass("disabled");

        $('#spinButton').addClass('disabled');
        $("#btnShuffle").addClass("disabled");
        $("#btnCollect").addClass("disabled");
    },
    setValueRate: function (data) {
        $("#txtReel_h1").html(COMMON.formatMoney(data.Rate.Column1WinForHigh));
        $("#txtReel_h2").html(COMMON.formatMoney(data.Rate.Column2WinForHigh));
        $("#txtReel_h3").html(COMMON.formatMoney(data.Rate.Column3WinForHigh));

        $("#txtReel_l1").html(COMMON.formatMoney(data.Rate.Column1WinForLow));
        $("#txtReel_l2").html(COMMON.formatMoney(data.Rate.Column2WinForLow));
        $("#txtReel_l3").html(COMMON.formatMoney(data.Rate.Column3WinForLow));

        $("#totalBids").html(COMMON.formatMoney(data.Info.AuCurrent + data.Info.AgCurrent));

        $("#shuffle_bar").html('');
        for (var i = 0; i < 6; i++) {
            if (i < data.Info.Nudges) {
                $("#shuffle_bar").append("<li><img src=\"/images/tg_1.jpg\" width=\"23\" height=\"23\" /></li>");
            } else {
                $("#shuffle_bar").append("<li><img src=\"/images/tg_2.jpg\" width=\"23\" height=\"23\" /></li>");
            }
        }
        if (data.Info.Nudges > 0) {
            $("#btnShuffle").removeClass("disabled");
        } else {
            $("#btnShuffle").addClass("disabled");
        }
        if (data.Info.Round > 0) {
            $("#btnCollect").removeClass("disabled");
        } else {
            $("#btnCollect").addClass("disabled");
        }
        if (data.Info.GameStatus == 5) {
            this.disableBet_style(true, data.Info.AuBet + data.Info.AgBet, data.Info.AuBet > 0 ? 1 : 2);
            $('.quay_nut1 a').removeClass("disabled");
            $('.quay_nut2 a').removeClass("disabled");

            if (data.Info.Column1Value == 13)
                $("#btnChoose_h1").addClass("disabled");
            if (data.Info.Column1Value == 1)
                $("#btnChoose_l1").addClass("disabled");

            if (data.Info.Column2Value == 13)
                $("#btnChoose_h2").addClass("disabled");
            if (data.Info.Column2Value == 1)
                $("#btnChoose_l2").addClass("disabled");

            if (data.Info.Column3Value == 13)
                $("#btnChoose_h3").addClass("disabled");
            if (data.Info.Column3Value == 1)
                $("#btnChoose_l3").addClass("disabled");
        } else {
            this.disableBet_style(false, 100, 1);
            $('.quay_nut1 a').addClass("disabled");
            $('.quay_nut2 a').addClass("disabled");
        }
    }
};
$('.disabled').live('click', function () {
    return false;
});
slotMachine.init();

function loadJackport() {
    $.ajax({
        url: "/Handler/UserControl/HandlerUCTriple7.ashx",
        type: "GET",
        data: { t: "LoadJackport" },
        dataType: "json",
        contentType: "application/json",
        success: function (data) {
            $("#spJackport").html(COMMON.formatMoney(data));
            setTimeout(loadJackport, 2000);
        },
        error: function () {

        }
    });
}

loadJackport();

buyitem = {
    showpopup: function () {
        this.closepopup();
        if ($('#divPopupBuyItem').length > 0)
            return;
        $("body").append('<div class="popup" id="divPopupBuyItem">'
            + '<div class="popup_bg">'
            + '<div class="title_popup"><a href="javascript:void(0)" onclick="buyitem.closepopup()">X</a>ĐỔI VÀNG</div>'
            + '<div id="divListItem"></div>'
            + '<div id="divListItemOut"></div>'
            + '</div></div>');
        COMMON.setTemplatePopup("#divPopupBuyItem");
        pages_paymentIn_ItemIn.documentReady();
        pages_paymentIn_ItemOut.documentReady();
    },
    closepopup: function () {
        if ($("#divPopupBuyItem").length > 0)
            $("#divPopupBuyItem").remove();
    }
}